#测试xml的操作
#读取xml中的某个属性
#写入xml的某个属性

from xml.etree import ElementTree
from xml.etree.ElementTree import Element
from xml.etree.ElementTree import SubElement
from xml.etree.ElementTree import dump
##from xml.etree.ElementTree import Comment
##from xml.etree.ElementTree import tostring
def print_node(node):
    print ("==============================================")
    print ("node.attrib:%s" % node.attrib)
    
import xml.dom.minidom as minidom

def indent( elem, level=0):
    i = "\n" + level*"  "
    if len(elem):
        if not elem.text or not elem.text.strip():
            elem.text = i + "  "
        for e in elem:
            indent(e, level+1)
        if not e.tail or not e.tail.strip():
            e.tail = i
    if level and (not elem.tail or not elem.tail.strip()):
        elem.tail = i
    return elem

##def GenerateXml():
##  import xml.dom.minidom
##  impl = xml.dom.minidom.getDOMImplementation()
##  dom = impl.createDocument(None, 'employees', None)
##  root = dom.documentElement  
##  employee = dom.createElement('employee')
##  root.appendChild(employee)
##  
##  nameE=dom.createElement('name')
##  nameT=dom.createTextNode('linux')
##  nameE.appendChild(nameT)
##  employee.appendChild(nameE)
##  
##  ageE=dom.createElement('age')
##  ageT=dom.createTextNode('30')
##  ageE.appendChild(ageT)
##  employee.appendChild(ageE)
##  
##
##  f= open('employees2.xml', 'w', encoding='utf-8')
##  dom.writexml(f, addindent='  ', newl='\n',encoding='utf-8')
##  f.close()  
##
##GenerateXml()

def readfromxml():
    # 1 通过getiterator
    root = ElementTree.parse('./test2.xml')
##    lst_node = root.getiterator("person")
##    for node in lst_node:
##        print_node(node)
##    # 2通过 getchildren
##        lst_node_child = lst_node[0].getchildren()[0]
##        print_node(lst_node_child)
## # 3 .find方法
##
##    node_find = root.find('person')
##    print_node(node_find)
###4. findall方法
##    tree = root.getroot()
##    tree.insert(0, Element("nonotest"))
##    node_find = root.find("nonotest")
##    SubElement(node_find, 'phone').text = "13764190064" #行增加
##
    node_findall = root.findall("person")
    tree = root.getroot()
    for oneper in node_findall:  #找出person节点
        print_node(oneper)
        if(oneper.find("phone") is  None):
            SubElement(oneper, 'phone').text = "13764190064" #行增加
        for child in oneper.getchildren(): #找出person节点的子节点
            print_node(child)
            print (child.tag,':',child.text)

    child = root.find('person').find('phone') #找到第一个person的phone,改变
    child.text = "12345"
    child.tag = "iPhone"
    node_findall = root.findall('person') #改变节点 里面的属性
    for oneper in node_findall:
        if (oneper.attrib.get("age") == "18"):
            oneper.attrib["age"] == "28"
        elif (oneper.attrib.get("age")is None):
            oneper.attrib["age"] = "15"

    indent(tree) 
    root.write('./test2.xml',"utf-8","xml")
#用xml.etree来写操作


def writetoxml():
    root = ElementTree.parse('./test2.xml')
    purchaseorder = Element('person')
    root._setroot(purchaseorder)
    SubElement(purchaseorder,  'account', {'refnum' : "2390094"})
    item = Element("item", {'sku' : '33-993933', 'qty' : '4'})
    purchaseorder.append(item)
    item = Element("name", {'name' : '33-993933', 'qty' : '4'})
    purchaseorder.append(item)
    print (item.items())
    SubElement(item, 'name').text = "Potato Smasher"
    SubElement(item, 'description').text = "Smash Potatoes like never before."
    root.write('./test2.xml',"utf-8","xml")
    dump(tree)
    #Element.insert(3, element) 


#用minidom来操作
import os  
import codecs  
import traceback  
import xml.dom.minidom as minidom   
def writetoxml2():
    doc = minidom.Document() 
     
    doc.appendChild(doc.createComment("Simple xml document__chapter 8")) 
     
    #generate the book 
    book = doc.createElement('book') 
    doc.appendChild(book) 
     
    #the title 
    title = doc.createElement('title') 
    title.appendChild(doc.createTextNode("sample xml thing")) 
    book.appendChild(title) 
     
    #the author section 
    author = doc.createElement("author") 
    book.appendChild(author) 
    name = doc.createElement('name') 
    author.appendChild(name) 
    firstname = doc.createElement('first') 
    firstname.appendChild(doc.createTextNode("ma")) 
    name.appendChild(firstname) 
    lastname = doc.createElement('last') 
    name.appendChild(lastname) 
    lastname.appendChild(doc.createTextNode("xiaoju")) 
     
    affiliation = doc.createElement("affiliation") 
    affiliation.appendChild(doc.createTextNode("Springs Widgets, Inc.")) 
    author.appendChild(affiliation) 
     
    #The chapter 
    chapter = doc.createElement('chapter') 
    chapter.setAttribute('number', '1') 
    title = doc.createElement('title') 
    title.appendChild(doc.createTextNode("First")) 
    chapter.appendChild(title) 
    book.appendChild(chapter) 
     
    para = doc.createElement('para') 
    para.appendChild(doc.createTextNode("I think widgets are greate.") )
    company = doc.createElement('company') 
    company.appendChild(doc.createTextNode("Spirngy Widgts, Inc")) 
    para.appendChild(company) 
    chapter.appendChild(para) 
 
 
    print (doc.toprettyxml() )
    
    f = open('./test2.xml',"rb")
##    writer = codecs.lookup('utf-8')[3](f)
    doc.writexml(f, encoding='utf-8')    
    writer.close()  
    f.close()  

def main():
   # readfromxml()#open("./test.xml").read()
   readfromxml()


if (__name__ == "__main__"):
      main()  
    
